import { Request, Response } from 'express'
import expressAsyncHandler from 'express-async-handler'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function jsonResponse<T>(fn: (req: Request, data?: any) => T, schema?: Zod.ZodSchema) {
  if (schema) {
    return (req: Request, res: Response) => {
      const parsed = schema.parse(req.body)
      const result = fn(req, parsed)
      res.json(result)
    }
  }
  return (req: Request, res: Response) => {
    const result = fn(req)
    res.json(result)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function asyncJsonResponse<T>(fn: (req: Request, data?: any) => Promise<T>, schema?: Zod.ZodSchema) {
  if (schema) {
    return expressAsyncHandler(async (req: Request, res: Response) => {
      const parsed = schema.parse(req.body)
      const result = await fn(req, parsed)
      res.json(result)
    })
  }
  return expressAsyncHandler(async (req: Request, res: Response) => {
    const result = await fn(req)
    res.json(result)
  })
}
